package com.ansion.utils.image;

import android.net.Uri;
import android.text.TextUtils;

import com.ansion.utils.FileUtil;


public class ImageManager {

    /**
     * 根据大图生成200x200的小图地址
     *
     * @param oldPreviewUrl
     * @return
     */

    public static String getAvatarPreUrl(String oldPreviewUrl) {
        if (oldPreviewUrl == null)
            return null;
        if (!oldPreviewUrl.startsWith("http")) {
            return oldPreviewUrl;
        }

        Uri parse = Uri.parse(oldPreviewUrl);
        String path = parse.getPath();

        if (TextUtils.isEmpty(path)) {
            return oldPreviewUrl;
        }

        String urlSuffix = FileUtil.getUrlSuffix(oldPreviewUrl);

        if (!TextUtils.isEmpty(urlSuffix)) {
            int index1 = oldPreviewUrl.lastIndexOf(".");
            oldPreviewUrl = oldPreviewUrl.substring(0, index1) + "_" + 200 + "x" + 200 + urlSuffix;
        } else {
            oldPreviewUrl = oldPreviewUrl + "_" + 200 + "x" + 200;
        }

        //AZusLog.d(TAG , "newimgUrl1 = " + oldPreviewUrl);
        return oldPreviewUrl;
    }

    /**
     * 根据小图地址生成大图地址
     *
     * @param oldPreviewUrl
     * @return
     */
    public static String getAvatarUrl(String oldPreviewUrl) {
        if (oldPreviewUrl == null)
            return null;
        if (!oldPreviewUrl.startsWith("http")) {
            return oldPreviewUrl;
        }

        String urlSuffix = FileUtil.getUrlSuffix(oldPreviewUrl);

        int index = oldPreviewUrl.lastIndexOf("_");
        if (index != -1) {
            oldPreviewUrl = oldPreviewUrl.substring(0, index) + urlSuffix;
        }
        //AZusLog.d(TAG , "newimgUrl1 = " + oldPreviewUrl);
        return oldPreviewUrl;
    }

    private static final String SUFFIX = ".png";
    private static final String SUFFIX2 = ".jpg";

    public static String getAvatrWithSpecifySize(String originalUrl, int width, int height) {
        if (TextUtils.isEmpty(originalUrl)) {
            return "";
        }
        String url = originalUrl;
        if (url.endsWith(SUFFIX)) {
            int index = url.lastIndexOf(SUFFIX);
            if (index != -1) {
                url = url.substring(0, index);
                if (height == 0) {
                    url += "_" + width + SUFFIX;
                } else {
                    url += "_" + width + "x" + height + SUFFIX;
                }
            }
        } else if (url.endsWith(SUFFIX2)) {
            int index = url.lastIndexOf(SUFFIX2);
            if (index != -1) {
                url = url.substring(0, index);
                if (height == 0) {
                    url += "_" + width + SUFFIX2;
                } else {
                    url += "_" + width + "x" + height + SUFFIX2;
                }
            }
        }

        return url;
    }
}
